package com.yhy.form.service.mng;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yhy.common.api.IWorkflowService;
import com.yhy.common.constants.BusModuleType;
import com.yhy.common.constants.BusSelfState;
import com.yhy.common.dto.workflow.WorkflowInfo;
import com.yhy.common.exception.BusinessException;
import com.yhy.common.service.BaseMngService;
import com.yhy.common.service.BaseSimpleMngService;
import com.yhy.common.utils.BusCenterHelper;
import com.yhy.common.utils.SpringContextHolder;
import com.yhy.common.utils.YhyUtils;
import com.yhy.common.vo.BusCommonState;
import com.yhy.form.dao.FormApplyMngDao;
import com.yhy.form.dto.FormApplyDTO;
import com.yhy.form.service.*;
import com.yhy.form.vo.*;
import com.yhy.form.vo.mng.FormApplyMngVO;
import com.yhy.form.vo.mng.FormSetMngVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-4-17 上午11:07 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */
@Service("formApplyMngService")
@Transactional(rollbackFor = Exception.class)
public class FormApplyMngService extends BaseSimpleMngService<FormApplyDTO, FormApplyMngVO> {

    @Autowired
    private FormApplyMngDao baseMngDao;
    @Autowired
    private FormSetMngService formSetMngService;
    @Autowired
    private FormSetMainService formSetMainService;
    @Autowired
    private FormSetContentService formSetContentService;
    @Autowired
    private FormSetFieldService formSetFieldService;
    @Autowired
    private FormSetFieldListService formSetFieldListService;
    @Autowired
    private FormSetFieldPrivService formSetFieldPrivService;
    @Autowired
    private FormApplyMainService applyMainService;
    @Autowired
    private FormApplyFieldValueService applyFieldValueService;

    @Override
    protected FormApplyMngDao getBaseMngDao() {
        return baseMngDao;
    }

    @Override
    public String getBusModule() {
        return BusModuleType.MD_FORM_APPLY_MNG.getVal();
    }

    @Override
    public FormApplyMainService getBaseMainService() {
        return applyMainService;
    }

    @Override
    protected void beforeSaveOfProcess(FormApplyDTO baseDTO) {
        super.beforeSaveOfProcess(baseDTO);
    }

    @Override
    protected void beforeSubmitOfWorkflowInfo(WorkflowInfo workflowInfo, FormApplyMngVO busMainData) {
        super.beforeSubmitOfWorkflowInfo(workflowInfo, busMainData);
        workflowInfo.setFormCode(busMainData.getFormCode());
        workflowInfo.setTaskTitle(busMainData.getApplyName() + "审批");
        workflowInfo.setTaskDesc(busMainData.getApplyName() + "审批");
    }

    @Override
    protected void afterProcessCustomDataOfChange(FormApplyDTO baseDTO, FormApplyMngVO busMainData) {
        super.afterProcessCustomDataOfChange(baseDTO, busMainData);

        String formId = busMainData.getFormId();
        FormSetContentVO formSetContentInfo = formSetContentService.findByMainId(formId);
        baseDTO.setFormContentInfo(formSetContentInfo);

        FormSetMainVO formSetMainVO = formSetMainService.findById(formId);
        baseDTO.setFormInfo(formSetMainVO);

        List<FormApplyFieldValueVO> applyFieldValueVOList = applyFieldValueService.findByMainId(busMainData.getOldMainId());
        baseDTO.setFormData(applyFieldValueService.convert2FormDataMap(applyFieldValueVOList));

        // 控件权限管控
        Map<String,Boolean> formDataVisible = Maps.newHashMap();
        Map<String,Boolean> formDataEditable = Maps.newHashMap();
        formSetFieldPrivService.setFormDataPriv(formId, YhyUtils.getSysUser().getUserAccount(), formDataEditable, formDataVisible);
        baseDTO.setFormDataEditable(formDataEditable);
        baseDTO.setFormDataVisible(formDataVisible);
    }

    @Override
    protected void afterProcessOfToView(FormApplyDTO baseDTO) {
        super.afterProcessOfToView(baseDTO);
        FormApplyMngVO busMainData = baseDTO.getBusMainData();

        String formId = busMainData.getFormId();
        FormSetContentVO formSetContentInfo = formSetContentService.findByMainId(formId);
        baseDTO.setFormContentInfo(formSetContentInfo);

        FormSetMainVO formSetMainVO = formSetMainService.findById(formId);
        baseDTO.setFormInfo(formSetMainVO);

        List<FormApplyFieldValueVO> applyFieldValueVOList = applyFieldValueService.findByMainId(busMainData.getId());
        baseDTO.setFormData(applyFieldValueService.convert2FormDataMap(applyFieldValueVOList));

        // 控件权限管控
        Map<String,Boolean> formDataVisible = Maps.newHashMap();
        Map<String,Boolean> formDataEditable = Maps.newHashMap();
        formSetFieldPrivService.setFormDataPriv(formId, YhyUtils.getSysUser().getUserAccount(), formDataEditable, formDataVisible);
        baseDTO.setFormDataEditable(formDataEditable);
        baseDTO.setFormDataVisible(formDataVisible);
    }

    @Override
    protected void processOfToCopy(FormApplyDTO baseDTO) {
        super.processOfToCopy(baseDTO);
        FormApplyMngVO busMainData = baseDTO.getBusMainData();

        List<FormSetMngVO> tmpFormSets = formSetMngService.getFormSetByCode(Sets.newHashSet(busMainData.getFormCode()));
        if(CollectionUtils.isEmpty(tmpFormSets)) {
            throw new BusinessException("当前复制的表单无效"+busMainData.getFormCode());
        }
        busMainData.setFormId(tmpFormSets.get(0).getId());
        String formId = busMainData.getFormId();
        FormSetContentVO formSetContentInfo = formSetContentService.findByMainId(formId);
        baseDTO.setFormContentInfo(formSetContentInfo);

        FormSetMainVO formSetMainVO = formSetMainService.findById(formId);
        baseDTO.setFormInfo(formSetMainVO);

        //拷贝值明细
        List<FormApplyFieldValueVO> applyFieldValueVOList = applyFieldValueService.findByMainId(busMainData.getOldMainId());
        baseDTO.setFormData(applyFieldValueService.convert2FormDataMap(applyFieldValueVOList));

        // 控件权限管控
        Map<String,Boolean> formDataVisible = Maps.newHashMap();
        Map<String,Boolean> formDataEditable = Maps.newHashMap();
        formSetFieldPrivService.setFormDataPriv(formId, YhyUtils.getSysUser().getUserAccount(), formDataEditable, formDataVisible);
        baseDTO.setFormDataEditable(formDataEditable);
        baseDTO.setFormDataVisible(formDataVisible);
    }

    @Override
    protected void processOfToAdd(FormApplyDTO baseDTO) {
        super.processOfToAdd(baseDTO);
        FormApplyMngVO paramBean = baseDTO.getParamBean();

        String formId = paramBean.getFormId();
        FormSetContentVO formSetContentInfo = formSetContentService.findByMainId(formId);
        baseDTO.setFormContentInfo(formSetContentInfo);

        FormSetMainVO formSetMainVO = formSetMainService.findById(formId);
        BusCommonState busCommonState = getBusCommonStateService().findByBusModuleAndMainId(getBusModule(), formId);
        baseDTO.setFormInfo(formSetMainVO);

        FormApplyMngVO busMainData = baseDTO.getBusMainData();
        busMainData.setFormId(formId);
        busMainData.setFormName(formSetMainVO.getFormName());
        busMainData.setFormType(formSetMainVO.getFormType());
        busMainData.setFormCode(busCommonState.getSysGenCode());
        busMainData.setApplyName(formSetMainVO.getFormName());

        // 控件权限管控
        Map<String,Boolean> formDataVisible = Maps.newHashMap();
        Map<String,Boolean> formDataEditable = Maps.newHashMap();
        formSetFieldPrivService.setFormDataPriv(formId, YhyUtils.getSysUser().getUserAccount(), formDataEditable, formDataVisible);
        baseDTO.setFormDataEditable(formDataEditable);
        baseDTO.setFormDataVisible(formDataVisible);
    }

    @Override
    protected void beforeSubmitOfProcess(FormApplyMngVO busMainData) {
        super.beforeSubmitOfProcess(busMainData);
    }

    @Override
    public void processBusCommonStateOfValid(FormApplyMngVO busMainData) {
        super.processBusCommonStateOfValid(busMainData);
    }

    private String getOptionListLabel(String fieldControlId, String fieldListValue, Map<String,String> filedListMap) {
        String newFieldValue = applyFieldValueService.arrStr2Str(fieldListValue);
        if(newFieldValue == null) {
            return null;
        }
        String rtnStr = "";
        String[] arrStr = newFieldValue.split(",");
        int i = 1, arrLen = arrStr.length;
        for (String val : arrStr) {
            rtnStr = rtnStr + filedListMap.get(fieldControlId + "-" + val) + (arrLen == i ? "" : "/");
            i++;
        }
        return rtnStr;
    }

    @Override
    protected void afterProcessCustomDataOfSave(FormApplyDTO baseDTO) {
        super.afterProcessCustomDataOfSave(baseDTO);
        FormApplyMngVO busMainData = baseDTO.getBusMainData();

        String formId = busMainData.getFormId();

        List<FormSetFieldVO> formSetFieldVOList = formSetFieldService.findByMainId(formId);
        List<FormSetFieldListVO> formSetFieldListVOList = formSetFieldListService.findByMainId(formId, null);

        Map<String,String> filedMap = Maps.newHashMap();
        formSetFieldVOList.stream().forEach(tmpvo -> {
            filedMap.put(tmpvo.getFieldControlId(), tmpvo.getFieldName());
        });
        Map<String,String> filedListMap = Maps.newHashMap();
        formSetFieldListVOList.stream().forEach(tmpvo -> {
            filedListMap.put(tmpvo.getFieldControlId() + "-" + tmpvo.getValue(), tmpvo.getLabel());
        });

        Map<String,Object> fieldDataMap = baseDTO.getFormData();
        //所有控件值处理, 先增加后删除
        String mainId = busMainData.getId();
        Map<String, String> existsFieldControlIds = Maps.newHashMap();
        List<FormApplyFieldValueVO> existsFieldVOS = applyFieldValueService.findByMainId(mainId);
        existsFieldVOS.stream().forEach(tmpvo -> {
            existsFieldControlIds.put(tmpvo.getFieldControlId(), tmpvo.getId());
        });
        for (Map.Entry<String, Object> fieldVO : fieldDataMap.entrySet()) {
            FormApplyFieldValueVO newFieldValue = new FormApplyFieldValueVO();
            newFieldValue.setMainId(mainId);
            newFieldValue.setEnableFlag("Y");
            newFieldValue.setFieldValue(fieldVO.getValue() == null ? "" : fieldVO.getValue().toString());
            newFieldValue.setFieldControlId(fieldVO.getKey());
            newFieldValue.setFieldName(filedMap.get(fieldVO.getKey()));
            newFieldValue.setFieldValueLabel(getOptionListLabel(fieldVO.getKey(),newFieldValue.getFieldValue(),filedListMap));

            if (existsFieldControlIds.containsKey(fieldVO.getKey())) {
                newFieldValue.setId(existsFieldControlIds.get(fieldVO.getKey()));
                existsFieldControlIds.remove(fieldVO.getKey());
                applyFieldValueService.update(newFieldValue);
                continue;
            }
            applyFieldValueService.insert(newFieldValue);
        }
        for (String pkid : existsFieldControlIds.values()) {
            FormApplyFieldValueVO deleteVo = new FormApplyFieldValueVO();
            deleteVo.setId(pkid);
            applyFieldValueService.deleteById(deleteVo);
        }
    }

    public Boolean checkExistProcessRecord(String formCode) {
        return getBaseMngDao().checkExistProcessRecord(formCode);
    }

}